package com.cloudkinto.service.company.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cloudkinto.common.common.DateUtils;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.dao.CompanyDao;
import com.cloudkinto.dao.UserDao;
import com.cloudkinto.entity.CompanyDo;
import com.cloudkinto.entity.CompanySecretKeyDo;
import com.cloudkinto.dao.CompanySecretKeyDao;
import com.cloudkinto.entity.UserDo;
import com.cloudkinto.service.company.CompanySecretKeyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;

import com.cloudkinto.session.UserSession;
import com.cloudkinto.session.UserSessionManager;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  service实现类
 * </p>
 * @author hua
 * @since 2023-06-08
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class CompanySecretKeyServiceImpl extends ServiceImpl<CompanySecretKeyDao, CompanySecretKeyDo> implements CompanySecretKeyService {
    @Autowired
    private CompanySecretKeyDao dao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private UserSessionManager userSessionManager;
    @Autowired
    private UserDao userDao;

    @Override
    public SingleResult addInit() {
        return SingleResult.success("");
    }

    @Override
    public Object secret(Long companyId, Long userId) {
        if (companyId == null) {
            throw new BizException(SysConstant.Login_Error_Company);
        }
        CompanyDo companyDo = companyDao.selectById(companyId);
        if (companyDo == null) {
            throw new BizException(SysConstant.Login_Error_Company);
        }
        //获取密钥，如果存在。设置密钥过期 5小时
        CompanySecretKeyDo lastDo = dao.selectOne(new LambdaQueryWrapper<CompanySecretKeyDo>()
                .eq(CompanySecretKeyDo::getCompanyId, companyId).last(" order by id desc limit 1"));
        if (lastDo != null) {
            lastDo.setExpireTime(DateUtils.passingDateHour(new Date(), 5));
            lastDo.setExpireBy(userId);
            dao.updateById(lastDo);
        }
        dao.deleteById(lastDo);
        CompanySecretKeyDo et = new CompanySecretKeyDo();
        et.setCreateBy(userId);
        et.setCreateTime(new Date());
        et.setCompanyId(companyId);
        et.setCompanySecret(UUID.randomUUID().toString().replace("-", ""));
        dao.insert(et);

        Map<String, String> result = new HashMap<>();
        result.put("key", companyDo.getCompanyCode());
        result.put("secret", et.getCompanySecret());
        return result;
    }

    /**
     * 根据密钥获取token
     * @param companyCode
     * @param companySecret
     * @return
     */
    @Override
    public String getTokenBySecret(String companyCode, String companySecret) {
        CompanyDo companyDo = companyDao.selectOne(new LambdaQueryWrapper<CompanyDo>()
                .eq(CompanyDo::getCompanyCode, companyCode));
        if (companyDo == null) {
            throw new BizException(SysConstant.No_Company_Info);
        }
        CompanySecretKeyDo et = dao.getSecret(companyDo.getId(), companySecret);
        if (et == null) {
            throw new BizException(SysConstant.Key_Error_Or_Expired);
        }
        //如果存在 则生成token 并保存到redis 中
        UserDo userDo = userDao.selectById(et.getCreateBy());
        if (userDo == null) {
            throw new BizException(SysConstant.NO_USER_INFO);
        }
        UserSession session = userSessionManager.createSession(userDo, true);
        return session.getSessionId();
    }


    //新增校验
    private void addCheck(Object req) {

    }

    //做新增之前要执行的业务定制处理
    private void handlerAddBefore(CompanySecretKeyDo entityDo, Long userId) {
        entityDo.setCreateBy(userId);
        entityDo.setCreateTime(new Date());
        entityDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
    }

    //将新增的do转换成要返回的实体
    private Object handlerAddAfter(CompanySecretKeyDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public SingleResult updateInit(Long id) {
        return SingleResult.success("");
    }

    @Override
    public Object update(Object req, Long userId) {
        /*CompanySecretKeyDo entityDo = dao.selectById(req.getId());
        BeanUtils.copyProperties(req, entityDo);
        handlerUpdateBefore(entityDo, userId);
        dao.updateById(entityDo);
        return handlerUpdateAfter(entityDo);*/
        return null;
    }

    //编辑校验
    private void updateCheck(Object req) {

    }

    //做修改之前要执行的业务定制处理
    private void handlerUpdateBefore(CompanySecretKeyDo entityDo, Long userId) {
    }

    //做修改之后要执行的业务定制处理
    private Object handlerUpdateAfter(CompanySecretKeyDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public int delete(Long id, Long userId) {
        CompanySecretKeyDo entityDo = dao.selectById(id);
        handlerDeleteBefore(entityDo, userId);
        return dao.deleteById(id);
    }

    //做删除之前要执行的业务定制处理
    private void handlerDeleteBefore(CompanySecretKeyDo entityDo, Long userId) {
    }

    @Override
    public Object detail(Long id) {
        CompanySecretKeyDo entityDo =  dao.selectById(id);
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return handlerDetailAfter(res);
    }

    //查询明细之后要执行的业务定制处理
    private Object handlerDetailAfter(Object res) {
        return res;
    }

    @Override
    public SingleResult pageInit() {
        return SingleResult.success("");
    }

    @Override
    public List<Object> getList(Map<String, String> map) {
        QueryWrapper<CompanySecretKeyDo> wrapper = queryBuild(map);
        List<CompanySecretKeyDo> list = this.list(wrapper);
        List<Object> result = handlerListAfter(list);
        return result;
    }

    @Override
    public PageResult getListPage(Map<String, String> map) {
        QueryWrapper<CompanySecretKeyDo> wrapper = queryBuild(map);
        IPage<CompanySecretKeyDo> page = pageInit(map);
        page = this.page(page, wrapper);
        List<Object> resList = handlerListAfter(page.getRecords());
        PageResult result = new PageResult(resList, (int)page.getCurrent(), (int)page.getSize(), (int)page.getTotal(), (int)page.getPages());
        return result;
    }

    //查询分页列表之后对列表数据的处理
    private List<Object> handlerListAfter(List<CompanySecretKeyDo> list ){
        List<Object> result = new ArrayList<>();
        return result;
    }

    private IPage<CompanySecretKeyDo> pageInit(Map<String, String> map) {
        IPage<CompanySecretKeyDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<CompanySecretKeyDo> queryBuild(Map<String, String> map) {
        QueryWrapper<CompanySecretKeyDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("keyword"))) {
            wrapper.like("keyword", map.get("keyword"));
        }
        return wrapper;
    }


}
